const { JJCourseRefundApply, JJCourse, JJUserCourse, JJCourseCamp, JJUser } = require('../../models/ctcdb');
const BaseResp = require('../../utils/baseResp');
const errorCode = require('../../utils/errorCode');
const refundService = require('../pay/refund');
const _ = require('lodash');
const tools = require('../../utils/tools');

async function dealApply({ applyId, userId, status }) {
  const courseApply = await JJCourseRefundApply.findOne({
    where: {
      id: applyId,
      status: 0,
      handleUserId: userId
    },
    attributes:['courseId', 'applyUserId', 'type', 'handleUserId'],
    raw: true
  });
  if (!courseApply) {
    throw BaseResp.error(errorCode.APPLY.NOT_FOUND)
  }
  // 拒绝的话直接不同意
  if (Number(status) === -1) {
    return JJCourseRefundApply.update({
      status: -1
    }, {
      where: {
        id: applyId
      }
    })
  }
  const { courseId, applyUserId, handleUserId } = courseApply;
  const course = await JJCourse.findOne({
    where: {
      id: courseId,
      status: 1
    },
    attributes: ['id', 'type', 'isSend', 'totalMoney'],
    raw: true
  });
  if (!course) {
    throw BaseResp.error(errorCode.COURSE.NOT_FOUND)
  }
  const { type, isSend } = course;
  const { type: applyType } = courseApply;
  let buyUserId = handleUserId;
  // 说明是用户提起的申请
  if (applyType === 1) {
    buyUserId = applyUserId;
  }
  // 处理结果（如果不是定制的）
  if (!isSend) {
    const userCourse = await JJUserCourse.findOne({
      where: {
        state: 1,
        courseId,
        jUserId: buyUserId,
        type: 1
      },
      attributes: ['orderId', 'id', 'courseId'],
      raw: true
    });
    if (!userCourse) {
      throw BaseResp.error(500, '此用户课程已被结束，无需处理')
    }
    const { orderId } = userCourse;
    await refundService.refundNormalCourse({ orderId, type })
  } else {
    await refundService.refundMakeCourse({ courseId, userId: buyUserId, type });
  }
  // 修改申请
  await JJCourseRefundApply.update({
    status: 1
  }, {
    where: {
      id: applyId
    }
  })
  // todo 考虑下私人教练的这种是否要直接给下架 取消
}

async function queryRefundApplyList({ offset, limit, kind, userId }) {
  let where = {};
  if (kind === 0) {
    where = {
      $or: [{ applyUserId: userId }, { handleUserId: userId }]
    }
  }
  if (kind === 1) {
    where.applyUserId = userId
  }
  if (kind === 2) {
    where.handleUserId = userId
  }
  const [list, count] = await Promise.all([
    JJCourseRefundApply.findAll({
      where,
      attributes: ['refundStatus', 'status', 'type', 'courseId', 'applyUserId', 'handleUserId', 'createTime', 'id', 'remark'],
      order: [['id','desc']],
      offset,
      limit,
      raw: true
    }),
    JJCourseRefundApply.count({
      where
    })
  ]);
  const courseIds = [];
  const userIds = [];
  list.forEach((item) => {
    courseIds.push(item.courseId);
    userIds.push(item.applyUserId);
    userIds.push(item.handleUserId)
  });
  const [users, courses] = await Promise.all([
    JJUser.findAll({
      where: {
        id: userIds
      },
      attributes: ['name', 'id'],
      raw: true
    }),
    JJCourse.findAll({
      where: {
        id: courseIds
      },
      attributes: ['id', 'courseName', 'type'],
      raw: true
    })
  ]);
  const userMap = _.keyBy(users, 'id');
  const courseMap = _.keyBy(courses, 'id');
  list.map((item) => {
    item.applyUserName = userMap[item.applyUserId] && userMap[item.applyUserId].name || '';
    item.handleUserName = userMap[item.handleUserId] && userMap[item.handleUserId].name || '';
    item.courseName = courseMap[item.courseId] && courseMap[item.courseId].courseName || '';
    item.courseType = courseMap[item.courseId] && courseMap[item.courseId].type || 1;
    item.createTime = tools.formatDate(item.createTime);
    item.isSelf = 0;
    if (item.applyUserId === userId) {
      item.isSelf = 1;
    }
    return item;
  });
  return {
    list,
    count
  }
}

module.exports = {
  // 处理申请结果
  dealApply,
  // 查询申请列表
  queryRefundApplyList
};
